package com.one.blocks.mvc.util;

import lombok.experimental.UtilityClass;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.function.Supplier;

/**
 * @author <a href="mailto:idler41@163.con">linfuxin</a> created on 2023-11-06 22:15:34
 */
@UtilityClass
public class ScopeWebRequestHelper {

    public static <V> V get(String key, Supplier<V> supplier) {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        //noinspection unchecked
        V scopeData = (V) requestAttributes.getAttribute(key, RequestAttributes.SCOPE_REQUEST);
        if (scopeData != null) {
            return scopeData;
        }
        scopeData = supplier.get();
        requestAttributes.setAttribute(key, scopeData, RequestAttributes.SCOPE_REQUEST);
        return scopeData;
    }
}
